package com.lgl.scsapi.servlet;

import com.alibaba.fastjson.JSON;
import com.lgl.scsapi.util.utils.DragImageVerificationCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 初始化图形验证码servlet
 */
@Slf4j
@WebServlet(name = "imgVerifyCodeServlet",urlPatterns = {"/index/makeImgVerifyCode","/ventIndex/makeImgVerifyCode"})
public class ImgVerifyCodeServlet extends HttpServlet {
    @Value("${wx.upload.path}")
    private String verifyImgPath;

	@Override
    public void init(ServletConfig config) throws ServletException {
		super.init(config);
        DragImageVerificationCode.init(verifyImgPath.replaceAll("\\\\","/"));
    }
	@Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String imgname = request.getParameter("imgname");
        if(StringUtils.hasText(imgname)) {
            imgname = imgname.substring(imgname.lastIndexOf("/")+1, imgname.lastIndexOf("png")+3);
        }
        PrintWriter out = null;
        try {
            DragImageVerificationCode resourImg = new DragImageVerificationCode();
            Map<String, String> result = resourImg.create(request, imgname);
            out = response.getWriter();
            response.setContentType("application/json-rpc;charset=UTF-8");
            out.println(JSON.toJSONString(result));
        } catch (Exception e) {
            log.error("初始化图形验证码servlet报错：" + e.toString(),e);
        } finally {
            if(out != null) {
                out.close();
            }
        }
    }
	@Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    }
}
